import React, { useCallback, useEffect, useState, useImperativeHandle, forwardRef, useRef } from "react";
import { Form, Button, Input, Select, Tooltip, DatePicker, Col, Divider, Row, Dropdown, Menu, Space } from "antd";
import { SearchSimpleTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import { batchModifyOnlineInventoryGetUpdateSkuList } from "../../../service";
import { cloneDeep, debounce } from "lodash";
import { PrefixPlaceholder } from "@/views/components/PrefixPlaceholder";

// TODO:   相同 款式编码 合并行 (按ecSpuId)

export default forwardRef(({ selectedRows, operationItems, afterFetch }, ref) => {
	const getCellProps = (value, record, rowIndex) => {
		return {
			colSpan: 1,
			rowSpan: record.rowSpan,
			style: {}
		};
	};
	// 是否是抖音店铺
	const isDY = selectedRows.some(e => e.ecType == 15);
	const defaultColumns = [
		{
			title: "商品名称",
			code: "skuName",
			width: 150,
			search: {
				content: () => <Input key="skuName" placeholder="请输入商品名称" />
			},
			getCellProps
		},
		{
			title: "颜色规格",
			code: "skuSpec",
			width: 150,
			search: {
				content: () => <Input placeholder="请输入颜色规格" />
			}
		},
		{
			title: "款式编码",
			code: "spuCode",
			width: 150,
			search: {
				content: () => <Input placeholder="请输入款式编码" />
			},
			getCellProps
		},
		{
			title: "修改后的款式编码",
			code: "spuCode2",
			hidden: isDY,
			width: 150,
			render: (v, d, i) => (
				<Input
					key={"spuCode2" + d.uuid + v}
					defaultValue={v}
					onPressEnter={e => {
						updateTableDataByRow(d, "spuCode2", e.target.value);
					}}
					onBlur={e => {
						updateTableDataByRow(d, "spuCode2", e.target.value);
					}}
					placeholder="请输入款式编码"
					maxLength={30}
				/>
			),
			getCellProps
		},
		{
			title: "原始商品编码",
			code: "skuOriginalCode",
			width: 150,
			search: {
				content: () => <Input placeholder="请输入商品编码" />
			}
		},
		{
			title: "修改后的原始商品编码",
			code: "skuOriginalCode2",
			width: 150,
			render: (v, d, i) => (
				<Input
					key={"skuOriginalCode2" + d.uuid + v}
					defaultValue={v}
					onPressEnter={e => {
						updateTableDataByRow(d, "skuOriginalCode2", e.target.value);
					}}
					onBlur={e => {
						updateTableDataByRow(d, "skuOriginalCode2", e.target.value);
					}}
					placeholder="请输入商品编码"
					maxLength={30}
				/>
			)
		}
	];

	const [columns, setColumns] = useState(defaultColumns);

	const beforeQuerySearch = ({ API_DATA }) => {
		return {
			...API_DATA,
			operationItems, // 操作项，0，勾选的商品;1,勾选商品对应款式的所有商品
			ids: selectedRows.map(e => e.id).join(",") // 主键id集合
		};
	};
	const bjSort = function (arr, key) {
		const temp = cloneDeep(arr);
		temp.sort((a, b) => {
			const s1 = String(a[key] || "");
			const s2 = String(b[key] || "");

			if (isNaN(Number(s1)) || isNaN(Number(s1))) {
				let a1 = s1.toUpperCase();
				let a2 = s2.toUpperCase();
				if (a1 < a2) {
					return -1;
				}
				if (a1 > a2) {
					return 1;
				}
				return 0;
			} else {
				return Number(s1) - Number(s2);
			}
		});
		return temp;
	};

	const resetSourceData = d => {
		console.log("resetSourceData");
		// 按ecSpuId 排序
		const list = bjSort(d, "ecSpuId");
		// 获取合并列数量
		const mergeMap = {};
		list.forEach(e => {
			const key = e.ecSpuId;
			if (key) {
				if (mergeMap[key]) {
					mergeMap[key] = mergeMap[key] + 1;
				} else {
					mergeMap[key] = 1;
				}
			}
		});
		// 设置合并数据
		return list.map((e, index) => {
			const key = e.ecSpuId;
			return {
				...e,
				uuid: `id-${e.id}-ecSpuId-${e.ecSpuId}-sysSkuId-${e.sysSkuId}`,
				rowSpan: mergeMap[key]
			};
		});
	};
	const tableRequest = batchModifyOnlineInventoryGetUpdateSkuList;
	const tableKey = "ShopGoodsActionEditSkuCodeModalEditTable";

	const {
		selectedKeys,
		selectedRows: editTableCheckedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		updateDataSource,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey: "uuid",
		// ///
		columns,
		tableRequest,
		autoFetch: false,
		hasPagination: false,
		hasQuickSearch: false,
		searchSpan: 3,
		beforeQuerySearch,
		resetSourceData,
		hasColsSetting: false,
		afterFetch
	});

	const updateTableData = fn => updateDataSource(pre => cloneDeep(pre.map(fn)));
	// 行内编辑后，变更数据
	const debounceUpdate = (row, key, value) => {
		const cloneRow = cloneDeep(row);
		updateDataSource(pre => {
			console.log(value);
			return pre.map((item, i) => {
				// 原始item
				const cloneItem = cloneDeep(item);
				// 修改后的item
				const cloneItemChange = cloneDeep(item);
				cloneItemChange[key] = value;
				// 当前行
				if (cloneItem.uuid === cloneRow.uuid) return cloneItemChange;
				// 同SPU行
				if (key === "spuCode2" && cloneRow.ecSpuId && cloneRow.ecSpuId == cloneItem.ecSpuId) return cloneItemChange;
				return cloneItem;
			});
		});
	};
	const updateTableDataByRow = useCallback(debounceUpdate, [updateDataSource]);

	useImperativeHandle(ref, () => ({
		// 暴露给父组件的方法
		updateTableData,
		setTableData: d => updateDataSource(d),
		getTableData: () => dataSource,
		reFresh: () => fetchList()
	}));

	return (
		<>
			<SearchSimpleTable key={tableKey} {...searchSimpleTableProps} />
		</>
	);
});
